﻿using System.Collections.Generic;
using System.Dynamic;
using System.Linq;

namespace ExcelUnity.Importer.Wrappers.SheetDataBuilders
{
    public class DynamicDataBuilder
    {
        public static List<dynamic> CreateDynamicDataList(List<RowWrapper>? rows, List<ColumnWrapper>? columns)
        {
            if (rows == null || columns == null) return new List<dynamic>();

            var list = new List<dynamic>();
            var columnPropertyDic = columns.ToDictionary(m => m.ColumnIndex);
            foreach (var row in rows)
            {
                dynamic model = new ExpandoObject();
                foreach (var cellWrapper in row.Cells)
                {
                    if (columnPropertyDic.TryGetValue(cellWrapper.ColumnIndex, out ColumnWrapper column))
                        ((IDictionary<string, object>)model).Add(column.ColumnName, cellWrapper.Value);
                }
                list.Add(model);
                row.ModelData = model;
            }
            return list;
        }
    }
}
